package com.example.sunmiv1.utils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.example.sunmiv1.entity.HangOverInfo;
import com.example.sunmiv1.entity.PrintInfoBean;
import com.example.sunmiv1.utils.net.ACache;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import woyou.aidlservice.jiuiv5.ICallback;
import woyou.aidlservice.jiuiv5.IWoyouService;

//國內 兼容所有機型 ，NB55正版GMS A13除外
//https://gitee.com/noryox/printer-client

//海外 兼容所有機型 ，NB55正版GMS A13除外
//https://github.com/SZNoryox/PrinterClient
/**
 * Created by Administrator on 2018-10-19.
 */

public class printUtil {

    private static final String SERVICE＿PACKAGE = "woyou.aidlservice.jiuiv5";
    private static final String SERVICE＿ACTION = "woyou.aidlservice.jiuiv5.IWoyouService";

    public IWoyouService woyouService;
    public static printUtil mAidlUtil = new printUtil();
    private Context context;

    private printUtil() {
    }

    public static printUtil getInstance() {
        if (mAidlUtil == null) {
            synchronized (printUtil.class) {
                if (mAidlUtil == null) {
                    mAidlUtil = new printUtil();
                }
            }
        }
        return mAidlUtil;
    }

    /**
     * 連接服務
     *
     * @param context context
     */
    public void connectPrinterService(Context context) {
        this.context = context.getApplicationContext();
        Intent intent = new Intent();
        intent.setPackage(SERVICE＿PACKAGE);
        intent.setAction(SERVICE＿ACTION);
        context.getApplicationContext().startService(intent);
        context.getApplicationContext().bindService(intent, connService, Context.BIND_AUTO_CREATE);
    }

    /**
     * 斷開服務
     *
     * @param context context
     */
    public void disconnectPrinterService(Context context) {
        if (woyouService != null) {
            context.getApplicationContext().unbindService(connService);
            woyouService = null;
        }
    }

    public boolean isConnect() {
        return woyouService != null;
    }

    private ServiceConnection connService = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            woyouService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            woyouService = IWoyouService.Stub.asInterface(service);
        }
    };

    /**
     * 初始化打印機
     */
    public void initPrinter() {
        if (woyouService == null) {
            return;
        }
        try {
            woyouService.printerInit(null);
            woyouService.printerSelfChecking(new ICallback() {
                @Override
                public void onRunResult(boolean isSuccess) throws RemoteException {

                }

                @Override
                public void onReturnString(String result) throws RemoteException {

                }

                @Override
                public void onRaiseException(int code, String msg) throws RemoteException {

                }

                @Override
                public IBinder asBinder() {
                    return null;
                }
            });
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private static final String TAG = "printUtil";

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void print(PrintInfoBean printInfoBean) {
        if (woyouService == null) {
            return;
        }
        ACache aCache = ACache.get(context);
        try {
            woyouService.setAlignment(1, null);//設置對齊模式alignment 對齊方式 0--居左 , 1--居中, 2--居右
            woyouService.setFontSize(35, null);//設置字體大小
            woyouService.printText(aCache.getAsString("storeTag") + "\n", null);
            woyouService.printText("訂單詳情" + "\n", null);
            woyouService.printText("訂單類型:" + "\n", null);
            woyouService.setAlignment(0, null);//設置對齊模式alignment 對齊方式 0--居左 , 1--居中, 2--居右
            woyouService.sendRAWData(new byte[]{0x1B, 0x21, 0x08}, null);
            woyouService.setFontSize(22, null);

            String[] text = new String[4];
            int[] width = new int[]{3, 10, 7, 8};
            int[] align = new int[]{0, 2, 2, 2}; // 設置對齊方式0是左對齊，1居中，2右對齊
            text[0] = "名稱";
            text[1] = "數量";
            text[2] = "單價";
            text[3] = "金額";
            woyouService.printColumnsText(text, width, new int[]{1, 2, 2, 2}, null);

            woyouService.printTextWithFont("*****************************\n", "", 24, null);
            for (int i = 0; i < printInfoBean.getData().getGoods().size(); i++) {
                PrintInfoBean.DataBean.GoodsBean goodsBean = printInfoBean.getData().getGoods().get(i);
                woyouService.setAlignment(0, null);
                String goodsName = "";
                /*if (Double.parseDouble(goodsBean.getPlus_vip_price()) > 0 ||
                        Double.parseDouble(goodsBean.getVip_price()) > 0) { //會員價
                    goodsName = "#";
                }
                if (goodsBean.getVip_discount() != 1) { //會員折扣
                    goodsName = goodsName + "*";
                }*/
                if (goodsBean.getBefore_all_money() == 0) {
                    goodsName = goodsName + "贈:";
                }
                goodsName = goodsName + goodsBean.getGoods_name();
                woyouService.printText(goodsName + "\n", null);
                String[] texts = new String[4];
                int[] widths;
                widths = new int[]{3, 10, 7, 8};
                int[] aligns = new int[]{0, 2, 2, 2}; // 右齊,右齊,右齊
                texts[0] = "";
                if ("2".equals(goodsBean.getPricing_method())) {
                    texts[1] = "×" + goodsBean.getNum() + goodsBean.getCompany();
                } else {
                    texts[1] = "×" + goodsBean.getNum();
                }
                texts[2] = "" + goodsBean.getPrice(); // 打印文字
                texts[3] = "$" + goodsBean.getBefore_all_money();//
                woyouService.printColumnsText(texts, widths, aligns, null);
            }
            woyouService.printTextWithFont("*****************************" + "\n", "", 24, null);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日   HH:mm:ss");
            Date curDate = new Date(System.currentTimeMillis());
            woyouService.setFontSize(26, null);
            woyouService.printText("\n支付時間:\n" + formatter.format(curDate) + "\n", null);
            woyouService.printText("收銀員:" + aCache.getAsString("name") + "\n", null);
            woyouService.printText("訂單總金額:" + printInfoBean.getData().getBeforeAllMoney() + "\n", null);
            if (printInfoBean.getData().getVip_dis_money() > 0) {
                woyouService.printText("會員折扣: " + printInfoBean.getData().getVipInfo().getDiscount() + "(折扣金額" + printInfoBean.getData().getVip_dis_money() + ")\n", null);
            }
            if (printInfoBean.getData().getCoupon_money() > 0) {
                woyouService.printText("優惠券: $" + printInfoBean.getData().getCoupon_money() + "\n", null);
            }
            if (printInfoBean.getData().getSmall_changes_money() > 0) {
                woyouService.printText("抹零: $" + printInfoBean.getData().getSmall_changes_money() + "\n", null);
            }
            woyouService.printText("應收: $" + printInfoBean.getData().getAll_money() + "\n", null);
            String payList = "";
            double money = 0;
            for (int j = 0; j < printInfoBean.getData().getPayList().size(); j++) {
                String payItem = "";
                payItem = printInfoBean.getData().getPayList().get(j).getName() + ":" + printInfoBean.getData().getPayList().get(j).getMoney();
                if (printInfoBean.getData().getPayList().size() != j + 1) {
                    payItem = payItem + "\n" + "        ";
                }
                money = MathUtil.add(money, Double.parseDouble(printInfoBean.getData().getPayList().get(j).getMoney()));
                payList = payList + payItem;
            }
            money += printInfoBean.getData().getGive_change() + printInfoBean.getData().getZero_storage();
            woyouService.printText("實收: $" + printInfoBean.getData().getAmount_received() + "\n", null);//all_price - coupon - small_change
            woyouService.printText("支付方式: ", null);
            woyouService.printText(payList + "\n", null);
            String name = printInfoBean.getData().getVipInfo().getName();
            String phone = printInfoBean.getData().getVipInfo().getPhone();
            String balance = printInfoBean.getData().getVipInfo().getBalance();
            String integral = printInfoBean.getData().getVipInfo().getIntegral();
            if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(phone) && !TextUtils.isEmpty(balance) && !TextUtils.isEmpty(integral)) {

                woyouService.printText("會員姓名: ", null);
                woyouService.printText(name + "\n", null);

                woyouService.printText("會員手機號: ", null);
                woyouService.printText(phone + "\n", null);

                woyouService.printText("會員餘額: $", null);
                woyouService.printText(balance + "\n", null);

                woyouService.printText("會員積分: ", null);
                woyouService.printText(integral + "\n", null);
            }
            if ("2".equals(printInfoBean.getData().getIntegral_marketing())) {
                double moneyDisIntegral = printInfoBean.getData().getUse_integral();
                double integralDisMoney = printInfoBean.getData().getIntegral_dis_money();
                if (integralDisMoney > 0) {
                    woyouService.printText("購買積分:" + integralDisMoney + "元\n", null);
                }
                if (moneyDisIntegral > 0) {
                    woyouService.printText("積分扣除: " + moneyDisIntegral + "\n", null);
                }
            } else {
                if (printInfoBean.getData().getIntegral_dis_money() > 0) {
                    woyouService.printText("積分抵現: $" + printInfoBean.getData().getIntegral_dis_money() +
                            "(消耗積分" + printInfoBean.getData().getUse_integral() + ")\n", null);
                }
            }
            if (!TextUtils.isEmpty(printInfoBean.getData().getCashier_manual_money()) && Double.parseDouble(printInfoBean.getData().getCashier_manual_money()) != 0) {
                woyouService.printText("單品折扣: " + printInfoBean.getData().getCashier_manual_money() + "\n", null);
            }
            woyouService.setAlignment(1, null);//設置對齊模式alignment 對齊方式 0--居左 , 1--居中, 2--居右
//            woyouService.printText("\n#會員價   *店內會員折扣\n", null);
            woyouService.printText("謝謝惠顧\n", null);
            woyouService.printText("歡迎下次光臨", null);
            woyouService.lineWrap(8, null);
        } catch (RemoteException e) {
            e.printStackTrace();
            Toast.makeText(context, "打印錯誤！", Toast.LENGTH_SHORT).show();
        }

    }


    public void printHangOver(HangOverInfo hangOverInfo, boolean if_print, List<HangOverInfo.GoodsListBean> goodsList) {
        if (woyouService == null) {
            return;
        }
        ACache aCache = ACache.get(context);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss//獲取當前時間
        Date date = new Date(System.currentTimeMillis());
        try {
            woyouService.setAlignment(1, null);//設置對齊模式alignment 對齊方式 0--居左 , 1--居中, 2--居右
            woyouService.setFontSize(34, null);//設置字體大小
            woyouService.printText("交班憑條" + "\n", null);
            woyouService.lineWrap(1, null);
            woyouService.setAlignment(0, null);//設置對齊模式alignment 對齊方式 0--居左 , 1--居中, 2--居右
            woyouService.setFontSize(30, null);//設置字體大小
            woyouService.printText("在班人員：" + hangOverInfo.getCashier_name() + "\n", null);
            woyouService.printText("在班時間：" + hangOverInfo.getRecord_time() + "\n", null);
            woyouService.printText("值班門店：" + aCache.getAsString("storeTag") + "\n", null);
            woyouService.printText("現金金額：" + hangOverInfo.getPayList().getCash_amount() + "\n", null);
            woyouService.printText("微信金額：" + hangOverInfo.getPayList().getWeChat_amount() + "\n", null);
            woyouService.printText("支付寶金額：" + hangOverInfo.getPayList().getAli_amount() + "\n", null);
            woyouService.printText("會員金額：" + hangOverInfo.getPayList().getVip_amount() + "\n", null);
            woyouService.printText("會員充值(現金)：" + hangOverInfo.getPayList().getRecharge_cash_amount() + "\n", null);
            woyouService.printText("會員充值(微信)：" + hangOverInfo.getPayList().getRecharge_weChat_amount() + "\n", null);
            woyouService.printText("會員充值(支付寶)：" + hangOverInfo.getPayList().getRecharge_ali_amount() + "\n", null);
            woyouService.printText("其他金額：" + hangOverInfo.getPayList().getOther_amount() + "\n", null);
            woyouService.printText("會員充值贈送：" + hangOverInfo.getPayList().getRecharge_give_amount() + "\n", null);
            if (goodsList.size() > 0 && if_print) {
                woyouService.lineWrap(1, null);
                woyouService.printText("銷售明細:" + "\n", null);
                woyouService.printText("*************************" + "\n", null);
                for (int j = 0; j < goodsList.size(); j++) {
                    woyouService.printText(goodsList.get(j).getClass_name() + "\n", null);
                    String[] text = new String[3];
                    int[] width = new int[]{7, 7, 7};
                    text[0] = "名稱";
                    text[1] = "數量";
                    text[2] = "總價";
                    woyouService.printColumnsText(text, width, new int[]{1, 2, 2}, null);
                    for (int i = 0; i < goodsList.get(j).getGoods().size(); i++) {
                        woyouService.setAlignment(0, null);
                        String[] texts = new String[3];
                        int[] widths = new int[]{8, 8, 8};
                        int[] aligns = new int[]{1, 2, 2}; // 右齊,右齊,右齊
                        texts[0] = goodsList.get(j).getGoods().get(i).getGoods_name();
                        texts[1] = "×" + goodsList.get(j).getGoods().get(i).getNum();
                        texts[2] = MathUtil.round(goodsList.get(j).getGoods().get(i).getAll_money(), 2) + "";
                        woyouService.printColumnsText(texts, widths, aligns, null);
                    }
                    woyouService.printText("\n", null);
                }
                woyouService.printText("*************************" + "\n", null);

            }
            woyouService.lineWrap(6, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


}
